package br.edu.fucapi.pos.model.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import br.edu.fucapi.pos.model.bean.Associado;

public class AssociadoDAO {
	
	private EntityManager em;
	
	public EntityManager getEntityManager() {
	    EntityManagerFactory factory = Persistence.createEntityManagerFactory("ama");
	    EntityManager entityManager = factory.createEntityManager();
	    factory.close();

	    return entityManager;
	  }

	public AssociadoDAO(EntityManager em) {
		this.em = em;
	}
	
	public AssociadoDAO() {
	}
	
	@SuppressWarnings("unchecked")
	public List<Associado> pesquisar(Associado associado) {

		String hql = "from Associado associado";
		String conector = "";

		if (associado != null) {
			if (associado.getNome() != null && !associado.getNome().isEmpty()) {
				if (conector.isEmpty()) {
					conector = " where ";
				} else {
					conector = " and ";
				}
				hql = hql + conector + " upper(associado.nome) like :pNome ";
			}
			
		}
		
		hql = hql + " ORDER BY associado.nome ASC";

		Query query = getEntityManager().createQuery(hql);

		if (associado != null) {
			if (associado.getNome() != null && !associado.getNome().isEmpty()) {
				query.setParameter("pNome", "%" + associado.getNome().toUpperCase() + "%");
			}
			
		}

		List<Associado> lista = query.getResultList();

		return lista;
	}

}